package com.graduationpractice.dbot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.graduationpractice.dbot.biz.IUserService;
import com.graduationpractice.dbot.pojo.User;
import com.graduationpractice.dbot.tool.VerCodeGenerateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.Timer;
import java.util.TimerTask;


@Controller
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private IUserService iUserService;
//    private User user;


    //	获得发件人信息
    @Value("${spring.mail.username}")
    private String from;

    @RequestMapping(value = "/sendEmail", method = RequestMethod.POST)

    public String commonEmail(HttpSession session, String email) {
//        创建邮件消息
        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(from);

        message.setTo(email);

        message.setSubject("E-DB");

        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("email", email);
        User user = iUserService.getOne(queryWrapper);
        String userName = user.getUsername();
        UpdateWrapper<User> updateWrapper = new UpdateWrapper();

        String verCode = VerCodeGenerateUtil.generateVerCode();


        updateWrapper.set("VerCode", verCode);
        updateWrapper.eq("email", email);
        iUserService.update(user, updateWrapper);

        message.setText("【E-DB】\n尊敬的" + userName + ",您好:\n"
                + "您已经请求了重置密码，本次重置密码的验证码是：\n" + verCode + ",本验证码 5 分钟内效，请及时输入。（请勿泄露此验证码）\n"
                + "\n如非本人操作，请忽略该邮件。\n(这是一封通过自动发送的邮件，请不要直接回复）");
        user = iUserService.getOne(queryWrapper);
        session.setAttribute("checkUser", user);
        mailSender.send(message);

        try {
            final Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                User user;
                @Override
                public void run() {
                    updateWrapper.set("VerCode", "");
                    updateWrapper.eq("email", email);
                    iUserService.update(user, updateWrapper);
                }
            },5*60*1000);

        } catch (Exception e) {
            e.printStackTrace();
        }


        return "redirect:/checkvercode";
    }
}
